import { Component, Vue } from 'vue-property-decorator'
import styles from '../NewApply/NewApply.less'
import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import SealDetail from '../AppliedForMe/SealDetail'
import LossSeal from '../LossApply/LossSeal'
import TipsDialog from '@/components/TipsDialog'
import OperationCol from '@/components/OperationCol'
import SealStatus, { issueList } from '@/components/SealStatus'
import OrganizeTree from '@/components/OrganizeTree'
import {
  orgLicenseTypes,
  orgTypes,
  userLicenseTypes,
  adminTypes,
  useTypes,
  formatStatus,
  sealTypes,
  sealUseTypeList,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { UserState } from '../../store/modules/user'
import UnAuthorized from './UnAuthorized'
import user from '@/lib/request/user'
import { IResponse } from '@/lib/service'
import { Table } from 'element-ui'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class MyManagingSeal extends Vue {
  @State((state: RootState) => state.myManagingSeal.sealList)
  private sealList!: any[]
  @State((state: RootState) => state.myManagingSeal.total)
  private total!: number
  @State((state: RootState) => state.myManagingSeal.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.myManagingSeal.organizeUuid)
  private organizeUuid!: string
  @State((state: RootState) => state.lossApply.title)
  private lossTitle!: boolean
  @State((state: RootState) => state.lossApply.isEdit)
  private isLossEdit!: boolean
  @State((state: RootState) => state.lossApply.isLoss)
  private isLoss!: boolean
  @State((state: RootState) => state.lossApply.lossVisible)
  private lossVisible!: boolean
  @State((state: RootState) => state.myManagingSeal.loading)
  private loading!: boolean
  @State((state: RootState) => state.myManagingSeal.sealData)
  private sealData?: any
  @State((state: RootState) => state.user)
  private user!: UserState
  @State((state: RootState) => state.lossApply.saveLoading)
  private lossLoading!: boolean
  @State((state: RootState) => state.lossApply.content)
  private lossContent!: boolean

  private sealType: number[] = []
  private status: number[] = []
  private sealName: string = ''
  private pageIndex: number = 1
  private pageSize: number = 10
  private tipsVisible: boolean = false
  private sealApplyId = 0
  private sealApplyType = 0
  private sealRecordId = ''
  private tipsContent = ''
  private range: number = 2 // 1:仅本级部门 2:本级及下级
  private sealUseType: number[] = [] // 用章方式 1:Ukey签章 2:云签章
  private authorized: number = 0 // 是否被授权印章管理员 1:授权 2:未授权

  @Mutation('myManagingSeal/setStateData') private setStateData!: any
  @Mutation('lossApply/setStateData') private setLossStateData!: any
  @Action('myManagingSeal/getList') private getList!: any
  @Action('myManagingSeal/sealDetail') private sealDetail!: any
  @Action('lossApply/lossSealApply') private lossSealApply!: any
  @Action('recoverApply/recoverSealApply') private recoverSealApply!: any
  @Action('reissueApply/reissueApply') private reissueApply!: any

  protected render() {
    return (
      <div class={{ [styles.container]: true, p10: true }}>
        {this.authorized === 2 && (
          <UnAuthorized url={require('@/assets/seal-empty.svg')} />
        )}
        {this.authorized === 1 && (
          <OrganizeTree
            class={{ [styles.treeBlock]: true }}
            on-handle-node-click={this.handleNodeClick}
          />
        )}
        {this.authorized === 1 && (
          <div class={{ [styles.queryBlock]: true }}>
            <div class={{ [styles.query]: true, custom: true }}>
              <span class={styles.part}>
                <span>印章类别</span>
                <el-select
                  v-model={this.sealType}
                  multiple
                  collapse-tags
                  placeholder="默认全部"
                >
                  {sealTypes.map((sealType: any, index: number) => (
                    <el-option
                      key={sealType.id}
                      label={sealType.value}
                      value={sealType.id}
                    />
                  ))}
                </el-select>
              </span>
              <span class={styles.part}>
                <span>印章状态</span>
                <el-select
                  v-model={this.status}
                  multiple
                  collapse-tags
                  placeholder="默认全部"
                >
                  {issueList.map((sealType: any, index: number) => (
                    <el-option
                      key={sealType.key}
                      label={sealType.text}
                      value={sealType.key}
                    />
                  ))}
                </el-select>
              </span>
              <span class={styles.part}>
                <span>印章名称</span>
                <el-input v-model={this.sealName} />
              </span>
              <span class={styles.part}>
                <span>检索范围</span>
                <el-select v-model={this.range} disabled={!this.organizeUuid}>
                  <el-option label="本级及下级" value={2} />
                  <el-option label="仅本级部门" value={1} />
                </el-select>
              </span>
              <span class={styles.part}>
                <span>用章方式</span>
                <el-select multiple v-model={this.sealUseType}>
                  <el-option label="Ukey签章" value={1} />
                  <el-option label="云签章" value={2} />
                </el-select>
              </span>
              <span class={styles.part}>
                <el-button
                  plain
                  class="min color-blue"
                  loading={this.loading}
                  onClick={this.query}
                >
                  搜索
                </el-button>
                <el-button plain class="min color-gray" onClick={this.reset}>
                  重置
                </el-button>
              </span>
            </div>
            <el-table
              data={this.sealList}
              style="width: 100%"
              v-loading={this.loading}
              ref="table"
            >
              <TableEmpty
                v-show={!this.loading}
                slot="empty"
                url={require('@/assets/seal-empty.svg')}
                msg="当前查询条件下暂无印章数据"
              >
                <el-button onClick={this.toApplyPage}>前往申请印章</el-button>
                <el-button type="primary" onClick={this.toNewApply}>
                  前往查看申请记录
                </el-button>
              </TableEmpty>
              <el-table-column
                prop="sealCode"
                label="印章编码"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealName"
                label="印章名称"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="name"
                label="印章图片"
                min-width="100"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return (
                        <img
                          src={scope.row.sealPicUrl}
                          height="25"
                          alt="印章图片"
                        />
                      )
                    },
                  },
                }}
              />
              <el-table-column
                prop="sealType"
                label="印章类别"
                min-width="60"
                show-overflow-tooltip
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return formatStatus(sealTypes, scope.row.sealType)
                    },
                  },
                }}
              />
              <el-table-column
                prop="endTime"
                label="到期时间"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealUseType"
                label="用章方式"
                show-overflow-tooltip
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return formatStatus(
                        sealUseTypeList,
                        scope.row.sealUseType
                      )
                    },
                  },
                }}
              />
              <el-table-column
                prop="sealStatus"
                label="状态"
                min-width="100"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return <SealStatus issue status={scope.row.sealStatus} />
                    },
                  },
                }}
              />
              <el-table-column
                prop="id"
                label="操作"
                width="300"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return (
                        <span>
                          <OperationCol
                            operations={this.filterOptions(
                              scope.row.sealStatus,
                              scope.row.sealApplyType,
                              scope.row.sealUseType
                            )}
                            showNum={5}
                            row={scope.row}
                            index={scope.$index}
                          />
                        </span>
                      )
                    },
                  },
                }}
              />
            </el-table>
            {this.sealList && this.sealList.length > 0 && (
              <el-pagination
                class={{ [styles.pagination]: true }}
                onSize-change={this.handleSizeChange}
                onCurrent-change={this.handleCurrentChange}
                current-page={this.pageIndex}
                page-sizes={[10, 20, 30]}
                page-size={this.pageSize}
                layout="total, sizes, prev, pager, next, jumper"
                total={this.total}
                pager-count={5}
              />
            )}
          </div>
        )}

        <SealDetail
          detailItems={{
            eSealBasicInfo: true,
            sealOrgBasicInfo: true,
            sealUserBasicInfo: false,
            digitalCertBasicInfo: true,
            sealAdminBasicInfo: true,
          }}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ detailVisible: val })
          }}
          data={this.sealData}
          visible={this.detailVisible}
        >
          <template slot="sealAdminBasicInfo">
            <el-table
              data={this.sealData && this.sealData.managerAccounts}
              class={{ [styles.detailTable]: true }}
            >
              <el-table-column prop="name" label="印章管理员" />
              <el-table-column
                prop="mobile"
                label="手机号"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return <span>{desensitization(scope.row.mobile)}</span>
                    },
                  },
                }}
              />
            </el-table>
          </template>
        </SealDetail>
        <LossSeal
          onVisibleChange={(val: boolean) => {
            this.setLossStateData({ lossVisible: val })
          }}
          title={this.lossTitle}
          isEdit={this.isLossEdit}
          isLoss={this.isLoss}
          data={this.sealData}
          showSubmit
          saveLoading={this.lossLoading}
          onSave={this.lossOrRecover}
          visible={this.lossVisible}
          content={this.lossContent}
        />
        <TipsDialog
          onVisibleChange={(val: boolean) => {
            this.tipsVisible = val
          }}
          visible={this.tipsVisible}
          title="提示"
          btns={['关闭', '点击前往']}
          onConfirm={this.gotoRevokeDetail}
          content={this.tipsContent}
        />
      </div>
    )
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
      {
        id: 2,
        text: '补发',
        onClick: (index: number, rows: any) => {
          this.openReissue(rows)
        },
      },
      {
        id: 3,
        text: '吊销',
        onClick: (index: number, rows: any) => {
          this.openRevoke(rows)
        },
      },
      {
        id: 4,
        text: '挂失',
        onClick: (index: number, rows: any) => {
          this.openLoss(rows)
        },
      },
      {
        id: 5,
        text: '恢复',
        onClick: (index: number, rows: any) => {
          this.openRecover(rows)
        },
      },

      {
        id: 6,
        text: '应用管理',
        options: [
          {
            id: 1,
            text: '查看应用',
            onClick: (index: number, row: any) => {
              this.$router.push({
                name: 'manageSealRefProject',
                query: { sealCode: row.sealCode, type: row.sealUseType },
              })
            },
          },
          {
            id: 2,
            text: '授权应用',
            onClick: (index: number, row: any) => {
              this.$router.push({
                name: 'authProject',
                params: { type: 'auth' },
                query: {
                  sealCode: row.sealCode,
                  sealName: row.sealName,
                  sealType: formatStatus(sealTypes, row.sealType),
                },
              })
            },
          },
          {
            id: 3,
            text: '取消授权应用',
            onClick: (index: number, row: any) => {
              this.$router.push({
                name: 'authProject',
                params: { type: 'cancel' },
                query: {
                  sealCode: row.sealCode,
                  sealName: row.sealName,
                  sealType: formatStatus(sealTypes, row.sealType),
                },
              })
            },
          },
        ],
      },
      {
        id: 7,
        text: '应用管理',
        options: [
          {
            id: 1,
            text: '查看应用',
            onClick: (index: number, row: any) => {
              this.$router.push({
                name: 'manageSealRefProject',
                query: { sealCode: row.sealCode, type: row.sealUseType },
              })
            },
          },
        ],
      },
    ]

    return btns
  }

  get agentInfo() {
    return {
      agentName: this.user.accountName,
      agentId: this.user.accountUUID,
      agentMobile: this.user.accountMobile,
      agentLicenseType: this.user.accountLicenseType,
      agentLicenseNumber: this.user.accountLicenseNumber,
      agentMobileDes: desensitization(this.user.accountMobile),
      agentLicenseNumberDes: desensitization(this.user.accountLicenseNumber),
      agentLicenseTypeName: formatStatus(
        userLicenseTypes,
        this.user.accountLicenseType
      ),
    }
  }

  private async mounted() {
    await this.checkIsAuthManager()
    if (this.authorized === 1) {
      this.setStateData({ organizeUuid: '' })
      this.query()
    }
  }

  private async checkIsAuthManager() {
    const data: IResponse = await user.checkIsAuthManager()
    this.authorized = data.data ? 1 : 2
  }

  private handleNodeClick(val: any) {
    this.setStateData({ organizeUuid: val })
    this.query()
  }

  private filterOptions(
    status: number,
    sealApplyType: number,
    sealUseType: number
  ) {
    if (status === 1) {
      // 已发布
      return this.getOperations.filter(
        (item: any) =>
          item.id === 1 ||
          (sealUseType === 2 && item.id === 6) ||
          (sealUseType === 1 && item.id === 7) ||
          item.id === 4 ||
          (item.id === 3 && (sealApplyType === 0 || sealApplyType === 2))
      )
    } else if (status === 2) {
      // 已挂失
      return this.getOperations.filter(
        (item: any) =>
          item.id === 1 ||
          (sealUseType === 2 && item.id === 6) ||
          (sealUseType === 1 && item.id === 7) ||
          (item.id === 2 && (sealApplyType === 0 || sealApplyType === 6)) ||
          (item.id === 5 && sealApplyType !== 6) ||
          (item.id === 3 && (sealApplyType === 0 || sealApplyType === 2))
      )
    } else if (status === 3) {
      // 已吊销
      return this.getOperations.filter((item: any) => item.id === 1)
    } else if (status === 4) {
      return this.getOperations.filter(
        (item: any) =>
          item.id === 1 ||
          (sealUseType === 2 && item.id === 6) ||
          (sealUseType === 1 && item.id === 7)
      )
    }
  }

  private detail(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.setStateData({
        detailVisible: true,
        sealData: Object.assign({}, data, {
          organizeType: formatStatus(orgTypes, data.organizeType),
          organizeCardType: formatStatus(
            orgLicenseTypes,
            data.organizeCardType
          ),
          organizeLevel: formatStatus(adminTypes, data.organizeLevel),
          inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
          inspectMobileDes: desensitization(data.inspectMobile),
          inspectCardIdDes: desensitization(data.inspectCardId),
        }),
      })
      this.setStateData({ detailVisible: true })
    })
  }

  toApplyPage() {
    this.$router.push({ name: 'applyPage', params: { type: 'newApply' } })
  }

  toNewApply() {
    this.$router.push({ name: 'newApply' })
  }

  private query() {
    this.pageIndex = 1
    this.queryList()
  }
  private async queryList() {
    this.setStateData({ loading: true })
    await this.$nextTick()
    await this.getList({
      sealName: this.sealName,
      sealType: this.sealType,
      sealStatus: this.status,
      range: this.range,
      organizeUuid: this.organizeUuid,
      sealUseType: this.sealUseType,
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
    })
    const table = this.$refs.table as Table
    table.doLayout()
  }

  private handleSizeChange(val: number) {
    this.pageSize = val
    this.query()
  }

  private handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  private reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.range = 2
    this.sealUseType = []
    this.query()
  }

  private gotoRevokeDetail() {
    const path =
      this.sealApplyType === 2 ? '/home/revokeApply' : '/home/reissueApply'
    this.$router.push({
      path: path,
      query: { id: this.sealApplyId.toString(), recordId: this.sealRecordId },
    })
  }

  private async openRevoke(row: any) {
    const { sealApplyId, sealApplyRecordId, sealApplyType } = row
    this.sealApplyId = sealApplyId
    this.sealRecordId = sealApplyRecordId
    this.sealApplyType = sealApplyType
    if (sealApplyId !== 0) {
      // 获取已提交的吊销申请
      this.tipsContent = '当前印章已提交过吊销申请。'
      this.tipsVisible = true
    } else {
      this.$router.push({
        name: 'applyPage',
        params: { type: 'revokeApply' },
        query: { sealSn: row.sealSn },
      })
    }
  }

  private openLoss(row: any) {
    this.$router.push({
      name: 'applyPage',
      params: { type: 'lossApply' },
      query: { sealSn: row.sealSn },
    })
  }

  private openRecover(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.setStateData({
        sealData: Object.assign(
          {},
          data,
          {
            organizeType: formatStatus(orgTypes, data.organizeType),
            organizeCardType: formatStatus(
              orgLicenseTypes,
              data.organizeCardType
            ),
            organizeLevel: formatStatus(adminTypes, data.organizeLevel),
            inspectCardType: formatStatus(
              userLicenseTypes,
              data.inspectCardType
            ),
            sealType: formatStatus(sealTypes, data.sealType),
            sealUseType: formatStatus(useTypes, data.sealUseType),
            inspectMobileDes: desensitization(data.inspectMobile),
            inspectCardIdDes: desensitization(data.inspectCardId),
          },
          this.agentInfo
        ),
      })
      this.setLossStateData({
        lossVisible: true,
        isEdit: false,
        isLoss: false,
        title: '印章挂失恢复申请',
        content: '挂失',
      })
    })
  }

  private openReissue(row: any) {
    const { sealApplyId, sealApplyRecordId, sealApplyType } = row
    this.sealApplyId = sealApplyId
    this.sealRecordId = sealApplyRecordId
    this.sealApplyType = sealApplyType
    if (sealApplyId !== 0) {
      // 获取已提交的补发申请
      this.tipsContent = '当前印章已提交过补发申请。'
      this.tipsVisible = true
    } else {
      this.$router.push({
        name: 'applyPage',
        params: { type: 'reissueApply' },
        query: { sealSn: row.sealSn },
      })
    }
  }

  lossOrRecover(data: { isLoss: boolean; seal: any; isReissue: boolean }) {
    this.setLossStateData({ saveLoading: true })
    if (data.isReissue) {
      // 补发申请
      this.reissueApply({
        sealSn: data.seal.sealSn,
        applyReason: data.seal.reason,
      })
        .then((res: any) => {
          this.$message.success('补发申请已提交')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })

      return
    }
    if (data.isLoss) {
      // 挂失
      this.lossSealApply({
        sealSn: data.seal.sealSn,
        applyReason: data.seal.reason,
      })
        .then((res: any) => {
          this.$message.success('挂失成功')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })
    } else {
      // 恢复
      this.recoverSealApply(data.seal.sealSn)
        .then((res: any) => {
          this.$message.success('恢复成功')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })
    }
  }
}
